<?php

namespace App\Http\Controllers;

use App\Exceptions\InvalidRequestException;
use App\Models\OrderItem;
use App\Models\Product;
use Illuminate\Http\Request;

class ProductsController extends Controller
{
    /**
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function index(Request $request)
    {
        $order = $request->input('order', '');
        $search = $request->input('search', '');

        $products = Product::where('on_sale', true)
            ->when($search, function ($query) use ($search){ // 搜索
                $like = '%'.$search.'%';
                $query->where(function ($query) use ($like){
                    $query->where('title', 'like', $like)
                        ->orWhere('description', 'like', $like)
                        ->orWhereHas('skus', function ($query) use ($like){
                            $query->where('title', 'like', $like)
                                ->orWhere('description', 'like', $like);
                        });
                });
            })->when($order, function ($query) use ($order){ // 排序
                if (!preg_match('/^(.+)_(asc|desc)$/', $order, $m)){
                    return;
                }

                if (!in_array($m[1], ['price', 'sold_count', 'rating'])){
                    return;
                }
                $query->orderBy($m[1], $m[2]);
            })->paginate();

        $filters = compact('search', 'order');
        return view('products.index', compact('products', 'filters'));
    }

    /**
     * @param Product $product
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     * @throws InvalidRequestException
     */
    public function show(Request $request, Product $product)
    {
        if (!$product->on_sale){
            throw new InvalidRequestException('商品未上架');
        }

        // 是否收藏
        $favored = false;
        if ($user = $request->user()){
            $favored = boolval($user->favoriteProducts()->find($product->id));
        }

        // 评价
        $reviews = OrderItem::where('product_id', $product->id)
            ->with(['order.user', 'productSku'])
            ->whereNotNull('reviewed_at') // 已评价
            ->orderBy('reviewed_at', 'desc')
            ->limit(10)
            ->get();

        return view('products.show', compact('product', 'favored', 'reviews'));
    }

    /**
     * 收藏商品
     *
     * @param Request $request
     * @param Product $product
     * @return array
     */
    public function favor(Request $request, Product $product)
    {
        $user = $request->user();
        if ($user->favoriteProducts()->find($product->id)){
            return [];
        }

        $user->favoriteProducts()->attach($product);
        return [];
    }

    /**
     * 取消收藏商品
     *
     * @param Request $request
     * @param Product $product
     * @return array
     */
    public function disfavor(Request $request, Product $product)
    {
        $user = $request->user();
        $user->favoriteProducts()->detach($product);
        return [];
    }

    /**
     * 收藏列表
     * 
     * @param Request $request
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function favorites(Request $request)
    {
        $products = $request->user()->favoriteProducts()->paginate();
        return view('products.favorites', compact('products'));
    }
}
